/* eslint-disable react/destructuring-assignment */
import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { connect } from 'dva';
import { Popconfirm, Table, Tooltip, Modal } from 'antd';
import { openNotificationWithIcon } from "../../../../utils/comm.js"
import styles from './TenantUserTable.less';

const deleteUser = (dispatch, payload, cb) =>
  dispatch({
    type: "tenantManagement/delTenantUser",
    payload,
  }).then(({ errCode, errMsg }) => {
    if (errCode !== 0) {
      openNotificationWithIcon(
        "error",
        "",
        errMsg || "操作失败",
      );
    } else {
      openNotificationWithIcon('success', '', '删除成功');
      if (cb) {
        cb();
      }
    }
  })

const handleDelete = (dispatch, tenantId, record, cb) => {
  const { userCode, id } = record;
  const payload = { tenantId, userCode };
  const deletePayload = { ...payload, id };
  dispatch({
    type: "tenantManagement/getAuthorizedApp",
    payload,
  }).then(({ errCode, datas }) => {
    if (errCode === 0 && datas) {
      Modal.confirm({
        title: `该用户已授权${datas}，是否确定删除`,
        okText: "确定",
        cancelText: "取消",
        onOk() {
          deleteUser(dispatch, deletePayload, cb); 
        },
        onCancel() {},
      });
    } else {
      deleteUser(dispatch, deletePayload, cb); 
    }
  });
};

const getColumns = (dispatch, id, deleteCallback) => [
  {
    title: "用户编号",
    dataIndex: "userCode",
    key: "userCode",
  },
  {
    title: "姓名",
    dataIndex: "userName",
    key: "userName",
  },
  {
    title: "组织名称",
    dataIndex: "userOrgDesc",
    key: "userOrgDesc",
    render: (text) => {
      let _text = text;
      if (text && text.length > 25) {
        _text = `${text.substr(0, 25)}...`;
      }
      return (
        <>
          {text.length > 25 ? (
            <Tooltip overlayClassName={styles.tooltip} title={text}>
              <span>{_text}</span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          )}
        </>
      );
    },
  },
  {
    title: "添加时间",
    dataIndex: "createTime",
    key: "createTime",
  },
  {
    title: "操作",
    key: "opearation",
    render: (text, record) => {
      return (
        <Popconfirm
          title="确定要删除？"
          onConfirm={(e) => {
            e.preventDefault();
            handleDelete(dispatch, id, record, deleteCallback);
          }}
          okText="确定"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>
      );
    },
  },
];

const removeDuplicated = (arr) => {
  const key = {};
  let newArr = [];
  newArr = arr.filter((item) => {
    if (key[item.userCode]) return false;
    key[item.userCode] = true;
    return true;
  });

  return newArr;
};
const getListUsers = (dispatch, payload) => 
  dispatch({
    type: "tenantManagement/listUsers",
    payload,
  }).then(({ errCode, errMsg, datas, totalCount = 0 }) => {
    if (errCode !== 0) {
      openNotificationWithIcon(
        "error",
        "",
        errMsg || "获取已关联租户的用户列表失败",
      );
      return { total: 0, data: [] };
    } else {
      const data = removeDuplicated(datas);
      return { total: totalCount || data.length , data };
    }
  });

const TenantUserTable = (props) => {
  const { dispatch, loading, id, getReload } = props;

  const reload = useCallback(() => setPageOption({...pageOption}), [pageOption]);

  useEffect(() => {
    if (getReload) {
      getReload(reload);
    }
    return () => {
      getReload(null);
    }
  }, [getReload, reload])


  const columns = useMemo(() => getColumns(dispatch, id, reload), [dispatch, id, reload]);

  const [pageOption, setPageOption] = useState({
    current: 1,
    pageSize: 6,
  });

  const [data, setData] = useState([]);
  const [totalCount, setTotalCount] = useState([]);

  const tableLoading = loading.effects['tenantManagement/listUsers']
    || loading.effects['tenantManagement/delTenantUser']
    || loading.effects['tenantManagement/getAuthorizedApp'];

  useEffect(() => {
    if (id && id !== '-') {
      getListUsers(dispatch, { tenantId: id, ...pageOption })
        .then(({ total, data: _data }) => {
          setTotalCount(total);
          setData(_data);
        });
    } else {
      setData([]);
    }
  }, [pageOption, id]);

  return (
    <Table
      style={{
        minHeight:
          window.innerHeight -
          64 -
          16 -
          16 -
          48 -
          16 -
          165 -
          104 -
          57 -
          24 -
          25,
      }}
      columns={columns}
      rowKey="userCode"
      loading={!!tableLoading}
      dataSource={data}
      onChange={o => setPageOption(o)}
      pagination={{
        size: "small",
        total: totalCount,
        showSizeChanger: true,
        showQuickJumper: true,
        ...pageOption,
        pageSizeOptions: ["6", "10", "20", "30"],
      }}
    />
  )

};

export default connect(({ loading }) => ({
  loading,
}))(TenantUserTable);